package com.meihuayishu.backend.controller;

import com.meihuayishu.backend.common.ApiResponse;
import com.meihuayishu.backend.dto.UserDivinationSettingsDTO;
import com.meihuayishu.backend.entity.DivinationFeedback;
import com.meihuayishu.backend.entity.User;
import com.meihuayishu.backend.entity.UserDivinationSettings;
import com.meihuayishu.backend.repository.FeedbackRepository;
import com.meihuayishu.backend.repository.SettingsRepository;
import com.meihuayishu.backend.repository.UserRepository;
import com.meihuayishu.backend.service.FeedbackService;
import com.meihuayishu.backend.util.DivinationAccuracyAnalyzer;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import jakarta.persistence.EntityNotFoundException;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 用户占卜设置控制器
 * 管理用户的个性化占卜设置
 */
@RestController
@RequestMapping("/api/user/divination-settings")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "用户占卜设置", description = "管理用户的个性化占卜设置")
public class SettingsController {
    
    private final UserRepository userRepository;
    private final FeedbackRepository feedbackRepository;
    private final FeedbackService feedbackService;
    private final SettingsRepository settingsRepository;
    private final DivinationAccuracyAnalyzer accuracyAnalyzer;
    
    /**
     * 获取用户占卜设置
     * @param userId 用户ID
     * @return 用户占卜设置
     */
    @GetMapping("/{userId}")
    @Operation(summary = "获取用户占卜设置", description = "获取指定用户的占卜设置和统计信息")
    public ApiResponse<UserDivinationSettingsDTO> getUserDivinationSettings(@PathVariable Long userId) {
        try {
            // 获取用户信息
            User user = userRepository.findById(userId)
                .orElseThrow(() -> new EntityNotFoundException("用户不存在"));
            
            // 获取用户占卜设置
            Optional<UserDivinationSettings> settingsOptional = settingsRepository.findByUserId(userId);
            
            // 创建设置DTO
            UserDivinationSettingsDTO settingsDTO = new UserDivinationSettingsDTO();
            settingsDTO.setUserId(user.getId());
            settingsDTO.setUsername(user.getUsername());
            settingsDTO.setBirthLocation(user.getBirthLocation());
            settingsDTO.setCurrentCity(user.getCurrentCity());
            settingsDTO.setGender(user.getGender());
            settingsDTO.setMoodStatus(user.getMoodStatus());
            
            // 如果有设置，使用设置值；否则使用默认值
            if (settingsOptional.isPresent()) {
                UserDivinationSettings settings = settingsOptional.get();
                settingsDTO.setUseRealSolarTime(settings.getUseRealSolarTime());
                settingsDTO.setApplyFeedback(settings.getApplyFeedback());
                settingsDTO.setPriorityFactor(settings.getPriorityFactor());
                settingsDTO.setPreferredAiProvider(settings.getPreferredAiProvider());
            } else {
                // 默认设置
                settingsDTO.setUseRealSolarTime(true);
                settingsDTO.setApplyFeedback(true);
                settingsDTO.setPriorityFactor(null);
                settingsDTO.setPreferredAiProvider("zhipu"); // 默认使用智谱AI
            }
            
            // 获取统计信息
            long totalDivinations = feedbackRepository.countByUserId(userId);
            double accuracyRate = accuracyAnalyzer.getUserAccuracyRate(userId);
            
            settingsDTO.setTotalDivinations((int) totalDivinations);
            settingsDTO.setAccuracyRate(accuracyRate);
            
            // 获取最近的反馈记录
            List<DivinationFeedback> recentFeedbacks = accuracyAnalyzer.getUserRecentFeedback(userId, 5);
            settingsDTO.setRecentFeedbacks(recentFeedbacks);
            
            return ApiResponse.success(settingsDTO);
        } catch (Exception e) {
            log.error("获取用户占卜设置失败", e);
            return ApiResponse.error(400, e.getMessage());
        }
    }
    
    /**
     * 更新用户占卜设置
     * @param settingsDTO 用户占卜设置
     * @return 更新后的用户占卜设置
     */
    @PutMapping
    @Operation(summary = "更新用户占卜设置", description = "更新用户的占卜设置")
    public ApiResponse<UserDivinationSettingsDTO> updateUserDivinationSettings(@RequestBody UserDivinationSettingsDTO settingsDTO) {
        try {
            // 获取用户信息
            User user = userRepository.findById(settingsDTO.getUserId())
                .orElseThrow(() -> new EntityNotFoundException("用户不存在"));
            
            // 更新用户基本信息
            if (settingsDTO.getCurrentCity() != null) {
                user.setCurrentCity(settingsDTO.getCurrentCity());
            }
            if (settingsDTO.getMoodStatus() != null) {
                user.setMoodStatus(settingsDTO.getMoodStatus());
            }
            
            // 保存用户信息
            userRepository.save(user);
            
            // 更新或创建用户占卜设置
            UserDivinationSettings settings = settingsRepository.findByUserId(settingsDTO.getUserId())
                .orElse(new UserDivinationSettings());
            
            settings.setUserId(settingsDTO.getUserId());
            
            if (settingsDTO.getUseRealSolarTime() != null) {
                settings.setUseRealSolarTime(settingsDTO.getUseRealSolarTime());
            }
            
            if (settingsDTO.getApplyFeedback() != null) {
                settings.setApplyFeedback(settingsDTO.getApplyFeedback());
            }
            
            if (settingsDTO.getPriorityFactor() != null) {
                settings.setPriorityFactor(settingsDTO.getPriorityFactor());
            }
            
            if (settingsDTO.getPreferredAiProvider() != null) {
                settings.setPreferredAiProvider(settingsDTO.getPreferredAiProvider());
            }
            
            // 保存设置
            settingsRepository.save(settings);
            
            // 返回更新后的设置
            settingsDTO.setBirthLocation(user.getBirthLocation());
            settingsDTO.setGender(user.getGender());
            
            return ApiResponse.success(settingsDTO);
        } catch (Exception e) {
            log.error("更新用户占卜设置失败", e);
            return ApiResponse.error(400, e.getMessage());
        }
    }
    
    /**
     * 获取城市卦象准确率分析
     * @return 城市卦象准确率分析
     */
    @GetMapping("/analysis/city-hexagram")
    @Operation(summary = "获取城市卦象准确率分析", description = "分析不同城市对不同卦象的准确率")
    public ApiResponse<Map<String, Map<String, Double>>> getCityHexagramAccuracyAnalysis() {
        try {
            Map<String, Map<String, Double>> analysis = accuracyAnalyzer.analyzeCityHexagramAccuracy();
            return ApiResponse.success(analysis);
        } catch (Exception e) {
            log.error("获取城市卦象准确率分析失败", e);
            return ApiResponse.error(400, e.getMessage());
        }
    }
    
    /**
     * 获取心情卦象准确率分析
     * @return 心情卦象准确率分析
     */
    @GetMapping("/analysis/mood-hexagram")
    @Operation(summary = "获取心情卦象准确率分析", description = "分析不同心情对不同卦象的准确率")
    public ApiResponse<Map<String, Map<String, Double>>> getMoodHexagramAccuracyAnalysis() {
        try {
            Map<String, Map<String, Double>> analysis = accuracyAnalyzer.analyzeMoodHexagramAccuracy();
            return ApiResponse.success(analysis);
        } catch (Exception e) {
            log.error("获取心情卦象准确率分析失败", e);
            return ApiResponse.error(400, e.getMessage());
        }
    }
    
    /**
     * 清除分析缓存
     * @return 操作结果
     */
    @PostMapping("/analysis/clear-cache")
    @Operation(summary = "清除分析缓存", description = "清除占卜准确性分析缓存")
    public ApiResponse<String> clearAnalysisCache() {
        try {
            accuracyAnalyzer.clearAnalysisCache();
            return ApiResponse.success("分析缓存已清除");
        } catch (Exception e) {
            log.error("清除分析缓存失败", e);
            return ApiResponse.error(400, e.getMessage());
        }
    }
}
